package com.ovopark.firecar.helper

import android.content.Context
import com.ovopark.firecar.utils.LanguageUtils.getRegisterLanguage
import com.ovopark.firecar.utils.StringUtils.Companion.replaceBlank
import java.util.*

/**
 * Created by Shawn on 2018/3/12.
 */
class NetHeaderHelper private constructor() {
    val timeZone: String?
        get() = Companion.timeZone


    val client: String?
        get() = Companion.client


    val version: String?
        get() = Companion.version



    val lang: String?
        get() = Companion.lang


    companion object {
        private var timeZone: String? = null
        private var client: String? = null
        private var version: String? = null
        private var lang: String? = null

        @Volatile
        private var netHeaderHelper: NetHeaderHelper? = null
        @JvmStatic
        val instance: NetHeaderHelper?
            get() {
                synchronized(NetHeaderHelper::class.java) {
                    if (netHeaderHelper == null) {
                        netHeaderHelper = NetHeaderHelper()
                    }
                }
                return netHeaderHelper
            }

        @JvmStatic
        fun initRegisterInfo(context: Context?, versionName: String?) {
            version = versionName
            lang = getRegisterLanguage(context)
            client = "Android"
            timeZone = currentTimeZone
        }

        @JvmStatic
        val registerInfo: String
            get() = encodeHeadInfo(
                " " + replaceBlank(client) + " " + replaceBlank(version)
                        + " " + replaceBlank(lang) + " " + replaceBlank(timeZone)
            )

        /**
         * head 中文编码
         *
         * @param headInfo
         * @return
         */
        private fun encodeHeadInfo(headInfo: String): String {
            val sb = StringBuilder()
            var i = 0
            val length = headInfo.length
            while (i < length) {
                val c = headInfo[i]
                if (c <= '\u001f' || c >= '\u007f') {
                    sb.append(String.format("\\u%04x", c.toInt()))
                } else {
                    sb.append(c)
                }
                i++
            }
            return sb.toString()
        }

        val currentTimeZone: String
            get() {
                val tz = TimeZone.getDefault()
                return tz.getDisplayName(false, TimeZone.SHORT)
            }
    }
}